import { Injectable } from '@nestjs/common';
import { CreatePublicityDto } from './dto/create-publicity.dto';
import { UpdatePublicityDto } from './dto/update-publicity.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Publicity } from './entities/publicity.entity';
import {
  GetPublicityDto,
  ReturnPublicityDtoList,
} from './dto/get-publicity.dto';
import { conditionUtilsSelect } from '../utils/db.help';

@Injectable()
export class PublicityService {
  constructor(
    @InjectRepository(Publicity)
    private publicityRepository: Repository<Publicity>,
  ) {}

  create(createPublicityDto: CreatePublicityDto) {
    return this.publicityRepository.save(createPublicityDto);
  }

  async findAll(query: GetPublicityDto) {
    const { page, limit, title } = query;
    const conditions = [{ field: 'title', value: title }];

    const queryBuilder = await this.publicityRepository.createQueryBuilder(
      'publicity',
    );
    const newQueryBuilder = conditionUtilsSelect<Publicity>(
      queryBuilder,
      conditions,
      'publicity',
    );

    const count = await newQueryBuilder.getCount();
    const content = await newQueryBuilder
      .skip((page - 1) * limit || 0)
      .take(limit || 10)
      .getMany();

    return {
      content,
      totalElements: count,
      totalPages: Number(page || 1),
    } as unknown as ReturnPublicityDtoList;
  }

  findOne(id: number) {
    return this.publicityRepository.findOne({ where: { id } });
  }

  async update(id: number, updatePublicityDto: UpdatePublicityDto) {
    const res = await this.findOne(id);
    const newRes = this.publicityRepository.merge(res, updatePublicityDto);
    return this.publicityRepository.save(newRes);
  }

  async remove(id: number) {
    const res = await this.findOne(id);
    return this.publicityRepository.remove(res);
  }
}
